package com.qiche.service2.impl;

import com.qiche.dto.MemberCardItemDto;
import com.qiche.mapper2.Card2Mapper;
import com.qiche.mapper2.SeckillSuccess2Mapper;
import com.qiche.mapper2.Store2Mapper;
import com.qiche.mapper2.User2Mapper;
import com.qiche.model.*;
import com.qiche.service.impl.BaseService;
import com.qiche.service2.Card2Service;
import com.qiche.util.DateTimeUtils;
import com.qiche.util.JsonRpcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @author chendezhi
 * @date 2018/3/27 17:26
 */
@Service
public class Card2ServiceImpl extends BaseService<Card2> implements Card2Service {
    @Autowired
    private Card2Mapper card2Mapper;

    @Autowired
    private Store2Mapper store2Mapper;

    @Autowired
    private SeckillSuccess2Mapper ss2Mapper;

    @Autowired
    private User2Mapper user2Mapper;
    @Override
    public Card2 selectActiveByCardId(Long cardId) {
        return card2Mapper.selectActiveByCardId(cardId);
    }


    @Override
    public List<MemberCardItemDto> selectPiccByMemberPhone(String memberPhone,String sortMoney,String piccMid) {
        return card2Mapper.selectPiccByMemberPhone(memberPhone,sortMoney,piccMid);
    }

    @Override
    public Map<String,Object> writeOffPicc(String cardCode, String piccUid, String piccMid) {
        Map<String, Object> resultMap =null;
        if(piccMid!=null && !"null".equals(piccMid) && piccUid== null) {
            resultMap =isUsed(cardCode, null,Long.parseLong(piccMid));
        }else {
           User2 loginUser= user2Mapper.selectByPrimaryKey(piccUid);
            resultMap = isUsed(cardCode, loginUser,null);
        }
        return resultMap;
    }


    @Override
    public Map<String, Object> isUsed(String cardcode, User2 loginUser, Long storeId) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {


            Card2 card = selectByCardCodeAndStatus(cardcode, "1");
            if (card == null) {
                map.put("code", 2);
                map.put("msg", "优惠券不存在或者已经被使用");
                return map;
            }
            // 因为外部系统的券Activity可能为NULL ，所以需要判断
            if (card.getActivityId() != null && card.getActivityId() != -1) {
                card = selectCardWithMemberAndActivity(cardcode, "1");
            }
            if(card!=null){
                map.put("code", 1);
                map.put("msg","OK");
            }

            // 判断活动是否需要wifi认证才能核销是访问认证api取回结果认证在线状态，否跳过认证
            if (card.getActivity().getNeedWifi() == 0) {
                // 取WiFi认证用户信息判断用户是否能核销本张卡券
                boolean isConnectWifi = false;

                    isConnectWifi = JsonRpcUtils.isConnectWifiByPhone(card.getMember().getPhone());

                // 判断是否通过WiFi认证上网
                if (!isConnectWifi) {
                    map.put("code", 0);
                    map.put("msg", "客户手机没有使用门店ap链接互联网");
                    return map;
                }
            }

            // 判断对应卡券是否在对应的地方使用 洗车店、和4s店的不能交叉使用

            // 核销账号不是门店

            Store2 store = null;
            if (loginUser != null) {
                store = loginUser.getStore();
            } else {
                store = store2Mapper.selectByPrimaryKey(storeId);
            }
            if (store == null || store.getStoreType() == null) {
                map.put("code", 0);
                map.put("msg", "该账号不能核销卡券");
                return map;
            }
            // 判断是不是洗车店 卡券类型wash 要和 店铺类型 (洗车店) 匹配
            if (!store.getStoreType().equals(card.getCardType())) {
                map.put("code", 0);
                map.put("msg", "该优惠券不能在本店使用");
                return map;
            }

            // 判断是否是在指定的门店使用
            if (card.getActivity().getUseStore() != null && !"".equals(card.getActivity().getUseStore())
                    && card.getActivity().getUseStore().indexOf("" + store.getId()) == -1) {
                map.put("code", 0);
                map.put("msg", "该优惠券不能在本店使用");
                return map;
            }

            // 判断是否在指定的地区使用
            if ((store.getRegionCode() == null || store.getRegionCode().equals(""))
                    || (card.getActivity().getUseRegion() != null && !"".equals(card.getActivity().getUseRegion())
                    && card.getActivity().getUseRegion().indexOf(store.getRegionCode()) == -1)) {
                map.put("code", 0);
                map.put("msg", "该优惠券不能在本地区使用");
                return map;
            }
            // 判断优惠券是否过期
			if(card.getUsePeriod()!=null){
                Integer get_days = DateTimeUtils.daysBetween(card.getReceivingDate(), new Date());
                if (get_days > card.getUsePeriod()) {
                    map.put("code", 0);
                    map.put("msg", "优惠券已超出使用期限");
                    return map;
                }
            }

            // 判断是否过期
            if (card.getVerifyBeginDate() != null && card.getVerifyEndDate() != null) {
                Date now = new Date();
                if (!(now.compareTo(card.getVerifyEndDate()) < 0 && now.compareTo(card.getVerifyBeginDate()) > 0)) {
                    map.put("code", 0);
                    map.put("msg", "优惠券不在使用期限之内");
                    return map;
                }
            }
            // 判断卡券是否在使用时间段
            if (!card.getAvailable().contains(DateTimeUtils.getWeekOfDate(new Date()))) {
                map.put("code", 0);
                map.put("msg", "不在可用时间内");
                return map;
            }

        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 0);
            map.put("msg", "出现错误");
            map.put("error", e.getMessage());
            return map;
        }
        return map;
    }



    /**
     * 检查 均发卡券, 是否是指定的门店核销
     *
     * @param map
     * @param card
     * @param store
     * @return
     */
    private boolean checkStoreMsg(Map<String, Object> map, Card2 card,Store2 store) {
        SeckillSuccess2 seckillSuccess = ss2Mapper.selectByIdWithStore(card.getMemberId(), card.getId());
        if (seckillSuccess != null && seckillSuccess.getStore() != null) {
            Long storeId = seckillSuccess.getStore().getId();
            if (storeId != null && !storeId.equals(store.getId())) {
                map.put("code", 0);
                map.put("msg", "请前往指定门店核销");
                return true;
            }
        }
        return false;
    }

    @Override
    public Card2 selectByCardCodeAndStatus(String cardCode, String status) {

        Example example = new Example(Card2.class);
        Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status", status);
        criteria.andEqualTo("cardCode", cardCode);

        List<Card2> cards = null;
        cards = card2Mapper.selectByExample(example);
        if (cards != null && cards.size() > 0) {
            return cards.get(0);
        } else {
            return null;
        }

    }


    @Override
    public Card2 selectCardWithMemberAndActivity(String cardCode, String status) {
        Card2Example example=new Card2Example();
        Card2Example.Criteria criteria=example.createCriteria();
        criteria.andCardCodeEqualTo(cardCode);
        criteria.andStatusEqualTo(status);
        List<Card2> cards = null;
        cards = card2Mapper.selectCardAndMembersByExample(example);
        if (cards != null && cards.size() > 0) {
            return cards.get(0);
        } else {
            return null;
        }

    }

    @Override
    public List<Card2> selectCardAndMembersByExample(Card2Example example) {
        return card2Mapper.selectCardAndMembersByExample(example);
    }

    @Override
    public Card2 selectCardAndMemberByCardCode(String cardcode) {
       return card2Mapper.selectCardAndMemberByCardCode(cardcode);
    }
    @Override
    public int batchInsert(List<Card2> cards) {
        return card2Mapper.batchInsert(cards);
    }
}
